package com.terabits.smartriver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mongodb.gridfs.GridFSDBFile;
import com.terabits.smartriver.constants.MongoDBEnum;
import com.terabits.smartriver.constants.result.BaseResp;
import com.terabits.smartriver.constants.result.ResultStatus;
import com.terabits.smartriver.meta.vo.RegionVO;
import com.terabits.smartriver.service.RegionService;
import com.terabits.smartriver.util.JsonUtils;
import com.terabits.smartriver.util.MongoManager;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class SysController {
    @Autowired
    private RegionService regionService;

    @Autowired
    private MongoManager mongoManager;

    @Value("classpath:static/data/area.json")
    private Resource areaRes;

    public static JSONArray areaData;

    static {
        try {
            areaData = JsonUtils.readJsonFromClassPath("static/data/level3.json", JSONArray.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "获得省-市-区)", tags = {"系统通用"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "-1:全部 0或者不传:有值的省市区 1:企业 2:项目 3:设备 4:所有设备名称 5：所有设备类型 6：盒子 7:街道 此时isSimple为区的id"),
            @ApiImplicitParam(name = "isSimple", value = "0或者不传:非简单 1:简单的"),
    })
    @RequestMapping(value = "/sys/cascadedlocation/get", method = RequestMethod.GET)
    public BaseResp getCascadedLocation(Integer type, Integer isSimple, String roleProjectNum) {
//        List<RegionVO> regionCascadedAll = regionService.getRegionCascadedAll();
//        return new BaseResp(ResultStatus.SUCCESS, regionCascadedAll);

        if (StringUtils.isEmpty(type)) {
            type = 0;
        }
        if (StringUtils.isEmpty(isSimple)) {
            isSimple = 0;
        }

        //全部省市区
        if (type == -1) {
            return new BaseResp(ResultStatus.SUCCESS, areaData);
        }
        return new BaseResp(ResultStatus.SUCCESS, regionService.getRegionCascaded(type, isSimple, roleProjectNum));

    }


    @ApiOperation(value = "添加文件", tags = {"系统通用"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1项目资料上传 2保养照片 3盒子资料上传 其他待添加"),
    })
    @RequestMapping(value = "/sys/file/upload", method = RequestMethod.POST)
    public BaseResp addFile(@RequestParam("file") MultipartFile file, Integer type) throws Exception {

        String gridFSBucket = MongoDBEnum.getGridFSBucket(type);
        if (gridFSBucket == null) {
            return new BaseResp(ResultStatus.error_record_not_found);
        }
        String fileId = mongoManager.insertGridFS(gridFSBucket, file, null);

        Map result = new HashMap();
        result.put("fileId", fileId);
        result.put("fileName", file.getOriginalFilename());
        return new BaseResp(ResultStatus.SUCCESS, result);
    }

    @ApiOperation(value = "下载文件", tags = {"系统通用"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1项目资料 2保养照片 3盒子资料"),
            @ApiImplicitParam(name = "fileId", value = "单个"),
    })
    @RequestMapping(value = "/sys/file/download", method = RequestMethod.GET)
    public void getFile(@RequestParam("fileId") String fileId, Integer type, HttpServletResponse response) throws Exception {
        OutputStream os = response.getOutputStream();
        GridFSDBFile file = mongoManager.selectGridFS(MongoDBEnum.getGridFSBucket(type), fileId);
        if (file == null) {
            return;
        }

        String fileName = file.get("realFileName").toString();
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType(file.getContentType());
        file.writeTo(os);
        os.flush();
        os.close();
    }


    @ApiOperation(value = "查看文件 批量", tags = {"系统通用"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1项目资料 2保养照片 "),
            @ApiImplicitParam(name = "fileIds", value = "多个 数组"),
    })
    @RequestMapping(value = "/sys/file/downloads", method = RequestMethod.GET)
    public void getReportImg(@RequestParam("fileIds") List<String> fileIds, Integer type, HttpServletResponse response) throws Exception {

        OutputStream os = response.getOutputStream();
        for (String fileId : fileIds) {
            GridFSDBFile file = mongoManager.selectGridFS(MongoDBEnum.getGridFSBucket(type), fileId);
            response.setContentType(file.getContentType());
            file.writeTo(os);
            os.flush();
        }
        os.close();
    }

}
